<template>
  <el-dialog v-if="load" title="批量打印" v-model="visible" append-to-body :close-on-click-modal="false" :z-index="2000"
    width="500px" @close="handleClose">
    <el-form label-position="top">
      <el-form-item label="选择打印文件">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" class="w-full"
          @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="checkeds" @change="handleCheckedChange">
          <el-checkbox v-for="city in optionList" :key="city" :label="city">{{
            city
          }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">打 印</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus';
import { resMessage } from '@/utils/res'
import { getLodop } from '@/utils/LodopFuncs'

const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

const emit = defineEmits(['close', 'success'])

const checkAll = ref(true)
const isIndeterminate = ref(false)
const checkeds = ref(['付款申请书', '采购回执合同', '付款凭证', '采购附件'])
const optionList = ['付款申请书', '采购回执合同', '付款凭证', '采购附件']

const handleCheckAllChange = (val) => {
  checkeds.value = val ? optionList : []
  isIndeterminate.value = false
}
const handleCheckedChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === optionList.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < optionList.length
}

// 打开弹窗
const list = ref([])
const open = async (p_ids) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  const res = await api.print({ p_ids })
  resMessage({
    res,
    success: (res) => {
      list.value = res.list
      checkAll.value = true
      visible.value = true
    },
    btnText: res.data.success ? '继续打印' : '',
    successText: '可打印',
    errorText: '不可打印',
  }).then(async res => {
    list.value = res.list
    checkAll.value = true
    visible.value = true
  })
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

const isPDF = (url) => url.substring(url.lastIndexOf('.') + 1).toLowerCase() === 'pdf'

// 提交
const submit = async () => {
  if (!checkeds.value.length) {
    ElMessage.error('请选择打印文件')
    return
  }
  const showLoading = () => loadings.submit = true
  const closeLoading = () => loadings.submit = false
  const LODOP = getLodop()
  if (!LODOP) return
  showLoading()
  for (const form of list.value) {
    LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4")
    LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT", 'Full-Width')
    // 付款申请书
    if (checkeds.value.includes('付款申请书')) {
      LODOP.NEWPAGEA()
      const html = `
      <h2 style='text-align: center;'>付款申请书</h2>
      <table style="border-spacing: 0;font-size: 14px" border="1" width="100%">
        <colgroup>
          <col style="width: 10%">
          <col style="width: 23%">
          <col style="width: 10%">
          <col style="width: 23%">
          <col style="width: 10%">
          <col style="width: 23%">
        </colgroup>
        <tr>
          <td>公司主体</td>
          <td>${form.basic.company_id_name}</td>
          <td>供应商</td>
          <td>${form.basic.supplier_name}</td>
          <td>结算方式</td>
          <td>${form.basic.period_name}</td>
        </tr>
        <tr>
          <td>收款人</td>
          <td>${form.basic.collect_name}</td>
          <td>收款账号</td>
          <td>${form.basic.collect_account}</td>
          <td>银行名称</td>
          <td>${form.basic.collect_bank}</td>
        </tr>
        <tr>
          <td>申请人</td>
          <td>${form.basic.create_user}</td>
          <td>期望付款时间</td>
          <td>${form.basic.except_payment_time}</td>
          <td>付款单号</td>
          <td>${form.basic.payment_no}</td>
        </tr>
        <tr>
          <td>申请付款类型</td>
          <td>${form.basic.apply_payment_type_name}</td>
          <td>支付币种</td>
          <td>${form.basic.payment_currency}</td>
          <td>申请付款金额</td>
          <td>${form.basic.apply_price}</td>
        </tr>
        <tr>
          <td>优惠</td>
          <td>${form.basic.discount_price}</td>
          <td>售后</td>
          <td>${form.basic.after_sale_price}</td>
          <td>折扣</td>
          <td>${form.basic.preferential_price}</td>
        </tr>
        <tr>
          <td>支付账号</td>
          <td>${form.basic.payment_account_name}</td>
          <td>飞书审核</td>
          <td>${form.basic.is_feishu_audit_name}</td>
          <td>备注</td>
          <td>${form.basic.remark}</td>
        </tr>
      </table>
      <h4 style='margin-bottom: 10px'>操作日志</h4>
      <table style="border-spacing: 0;font-size: 14px" border="1" width="100%">
        <tr>
          <td>操作人</td>
          <td>操作类型</td>
          <td>操作时间</td>
        </tr>
        ${form.log.map(d => `
        <tr>
          <td>${d.create_user}</td>
          <td>${d.log_type}</td>
          <td>${d.create_time}</td>
        </tr>
        `).join('\n')}
      </table>
      `
      LODOP.ADD_PRINT_HTM(20, 20, '210mm', '280mm', html)
    }

    // 付款凭证
    const fields = []
    if (checkeds.value.length && checkeds.value.includes('付款凭证')) {
      fields.push(...form.voucher)
    }

    // 采购回执合同
    if (checkeds.value.length && checkeds.value.includes('采购回执合同')) {
      fields.push(...form.contract)
    }

    // 采购附件
    if (checkeds.value.length && checkeds.value.includes('采购附件')) {
      fields.push(...form.attachment)
    }
    for (const d of fields) {
      LODOP.NEWPAGEA()
      if (isPDF(d)) {
        console.log('isPDF(d)', isPDF(d))
        LODOP.ADD_PRINT_PDF(20, 20, '210mm', '280mm', d.replace('https', 'http'))
      } else {
        const html = `
        <div style='width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;'>
          <img src="${d}" style='width: 100%;height: auto;max-width: 100%;max-height:100%' />
        </div>
        `
        LODOP.ADD_PRINT_HTM(20, 20, '210mm', '280mm', html)
      }
    }
  }
  LODOP.PREVIEW()
  await new Promise(reslove => setTimeout(reslove, list.value.length * 1000))
  closeLoading()
}

defineExpose({ open })
</script>
